package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static com.hmdp.utils.RedisConstants.COUNTE_BIT;
import static com.hmdp.utils.SystemConstants.START_TIME_STAMP;
@Component
public class RedisGenerateID {
    private StringRedisTemplate redisTemplate;

    private final static long START_TIMESTAMP;
    @Autowired
    public RedisGenerateID(StringRedisTemplate stringRedisTemplate) {
        redisTemplate = stringRedisTemplate;
    }

    static {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        try {
            date = df.parse(START_TIME_STAMP);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        START_TIMESTAMP = cal.getTimeInMillis();
    }

    /**
     * 生成全局唯一ID
     * @return
     */
    public Long generateId() {
        long timestamp = System.currentTimeMillis() - START_TIMESTAMP;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String todayTime = simpleDateFormat.format(new Date());
        //将key自加
        Long increment = redisTemplate.opsForValue().increment(todayTime);

        return (timestamp << COUNTE_BIT) | increment;
    }


}
